<template>
  <div class="table-wrapper" ref="tableWrapper">
    <!-- 解决表格宽度无限拉长的问题 table-wrapper 为flex: 1 引起的 用table-content 包着 -->
    <div class="table-content">
      <slot name="header" />
      <el-table
        ref="tableDom"
        :data="realTableData_parent"
        :height="datas.tableHeight"
        :summary-method="getSummaries"
        :show-summary="showSummary"
        :highlight-current-row="highlightCurrentRow"
        border
        style="margin-bottom: 10px"
        :row-style="rowStyle"
        :span-method="spanMethod"
        @row-click="rowClick"
        @selection-change="pitchonChange"
      >
        <template v-for="(column, $index) in realTableColumns">
          <template v-if="!column.hideColumn && table_control">
            <report-column
              v-if="column.type !== 'slot'"
              :key="$index"
              v-bind="column"
              @button-handle="buttonHandle"
            />
            <el-table-column
              v-else
              :key="$index + 'slot'"
              v-bind="column"
              :align="column.align || 'center'"
              :width="column.width"
            >
              <template v-slot:default="scope">
                <slot :name="column.prop" :row="scope.row"></slot>
              </template>
            </el-table-column>
          </template>
        </template>
      </el-table>
      <el-pagination
        v-if="paginationShow"
        :small="small"
        style="text-align: right"
        :current-page="datas.pagination.pageNum"
        :page-sizes="props.pageSizesList"
        :page-size="datas.pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="props.realTotal_parent"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <slot name="footer" />
    </div>
  </div>
</template>

<script setup lang="ts" name="report-table">
import {
  onMounted,
  reactive,
  nextTick,
  toRef,
  getCurrentInstance,
  ComponentInternalInstance,
  computed,
  ref
} from 'vue'
import reportColumn from './report-column.vue'
// 转为千分符
const millimeter = /(\d)(?=(\d{3})+\.)/g
const $emit = defineEmits([
  'handleSelectionChange',
  'rowClick',
  'pagination-change',
  'button-handle'
])
const { proxy } = getCurrentInstance() as ComponentInternalInstance

const props = defineProps({
  realTableColumns: {
    type: Array as any
  },
  currentPage: {
    type: Number
  },
  path: {
    type: String,
    default: ''
  },
  totalPath: {
    // 合计行的合计数据接口url
    type: String
  },
  request_method: {
    type: String,
    default: 'post'
  },
  small: {
    type: Boolean,
    default: false
  },
  paginationShow: {
    type: Boolean,
    default: true
  },
  pageSize: {
    type: Number,
    default: 1
  },
  realTableData_parent: {
    type: Array
  },
  realTotal_parent: {
    type: Number,
    default: 0
  },
  totalRowMap: {
    type: Object as any
  },
  totalFormatterType: {
    // 合计的金额形式
    type: String,
    default: ''
  },
  pageSizesList: {
    type: Array as any,
    default() {
      return [10, 20, 50, 100, 200, 1000]
    }
  },
  summaryTitle: {
    // 自定义统计行-合计:位置num，title内容
    type: Object,
    default: function () {
      return {}
    }
  },
  spanMethod: {
    type: Function as any
  },
  beforeSearch: {
    type: Function
  },
  valueClone: {
    type: Object,
    default: function () {
      return {}
    }
  },
  // 控制是否显示动态控制表头的
  table_control: {
    type: Boolean,
    default: true
  },
  maxHeight: {
    type: String,
    default: '900px'
  },
  highlightCurrentRow: {
    // 是否显示高亮
    type: Boolean,
    default: true
  },
  extraHeight: {
    type: Number,
    default: 180
  },
  tableHeightFlag: {
    type: Boolean,
    default: true
  },
  initGetDatas: {
    type: Boolean,
    default: true
  },
  rowStyle: {
    type: Function as any
  }
})
const datas = reactive({
  tableHeight: 0,
  page: 1,
  limit: props.paginationShow ? 10 : 9999,
  loading: false,
  multipleSelection: <any>[],
  totalRow: {} as any, // 合计行的合计数据
  resolve_self: null,
  pagination: {
    pageSize: props.paginationShow ? 10 : 9999,
    pageNum: 1
  }
})
const showSummary = computed(() => {
  if (props.totalRowMap && Object.keys(props.totalRowMap).length > 0) {
    return true
  } else {
    return false
  }
})

if (props.pageSize && props.pageSizesList.includes(props.pageSize)) {
  datas.pagination.pageSize = toRef(props, 'pageSize').value
}
onMounted(() => {
  calculateHeight()
})
const handleSizeChange = function (val: number) {
  datas.pagination.pageSize = val
  datas.pagination.pageNum = 1
  handlePaginationChange()
}
const handleCurrentChange = function (val: number) {
  datas.pagination.pageNum = val
  handlePaginationChange()
}
const pitchonChange = function (val: Array<[]>) {
  datas.multipleSelection = val
  $emit('handleSelectionChange', datas.multipleSelection)
}
// 行点击事件
const rowClick = function (row: any, column: any, event: any) {
  $emit('rowClick', row, column, event)
}
// 重置pageSize
const handlePaginationReset = function () {
  datas.pagination = {
    pageSize: datas.pagination.pageSize,
    pageNum: 1
  }
  handlePaginationChange()
}
const handlePaginationChange = function () {
  if (props.realTableData_parent) {
    // 更新父组件传进来的tableData
    $emit('pagination-change', { ...datas.pagination })
  }
}
const getPagination = function () {
  return {
    ...datas.pagination
  }
}
// 表格里面的一些按钮
const buttonHandle = function (button: any, val: any, index: any) {
  $emit('button-handle', button, val, index)
}
const getSummaries = function (param: { columns: any }) {
  const { columns } = param
  const sums: any[] = []
  columns.map((item: { property: string }, index: number) => {
    if (index === 0) {
      let num = 0,
        title = '合计'

      if (props.summaryTitle && Object.keys(props.summaryTitle).length) {
        num = props.summaryTitle.num ? props.summaryTitle.num : 0
        title = props.summaryTitle.title ? props.summaryTitle.title : '合计'
      }
      sums[index + num] = title
      return
    }
    if (Object.keys(props.totalRowMap).includes(item.property)) {
      // 金额-统一千分符
      if (props.totalFormatterType === 'thousandMark') {
        sums[index] = String(datas.totalRow[props.totalRowMap[item.property]]).replace(
          millimeter,
          '$1,'
        )
      } else {
        // sums[index] = datas.totalRow[datas.totalRowMap[item.property]];
        sums[index] =
          (sums[index] || '') + '  ' + (datas.totalRow[props.totalRowMap[item.property]] || '')
      }
    }
  })
  return sums
}

const tableDom = ref()
const clearSelection = function () {
  tableDom.value.clearSelection()
}
const setTableHeight = function (h: number) {
  datas.tableHeight = h
}
const calculateHeight = function () {
  nextTick(() => {
    let Style = getComputedStyle(proxy?.$refs.tableWrapper as HTMLElement)
    datas.tableHeight = props.tableHeightFlag ? parseInt(Style.height) - 42 : 0 // crumbs home-footer el-pagination margin
  })
}
</script>
<style lang="less" scoped>
.table-wrapper {
  flex: 1;
  width: 100%;
  padding: 0 20px;
  background: #fff;
  position: relative;

  .table-content {
    height: 100%;
    position: absolute;
    width: calc(100% - 40px);
  }

  :deep(.el-table) th {
    background: #f5f7fa;
  }
}

.mg_20r {
  margin-right: 20px !important;
}

.dialog-footer {
  display: block;
  margin-top: 20px;
}

.float_r {
  float: right;
  border: none;
  padding: 0;
}

.icon_table {
  font-size: 18px;
  background: #ddd;
}

.commpone_nav {
  height: 30px;
  border-bottom: 1px solid #333;
  margin-bottom: 10px;
}
</style>
